//
//  ItemViewController.m
//  DanTang
//
//  Created by honeyrr on 2017/9/4.
//  Copyright © 2017年 honeyrr. All rights reserved.
//

#import "ItemViewController.h"
#import "DTItemCollectionViewCell.h"
#import "ItemDetailViewController.h"

//cell静态标识
static NSString * const itemCollectionCellID = @"itemCollectionCellID";

@interface ItemViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(nonatomic, strong) UICollectionView *itemCollectionView;

@property(nonatomic, strong) NSMutableArray *items;

@property(nonatomic, copy) NSString *next_url;
@end

@implementation ItemViewController

#pragma mark - 数组、表格懒加载
-(NSMutableArray *)items
{
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

-(UICollectionView *)itemCollectionView
{
    if (!_itemCollectionView) {
        UICollectionView *vc = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
        vc.delegate = self;
        vc.dataSource = self;
        _itemCollectionView = vc;
    }
    return _itemCollectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MRRGBColor(240.0, 240.0, 240.0);
    
    [self setUpCollectionView];
}

-(void) setUpCollectionView
{
    //注册
    [self.itemCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DTItemCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:itemCollectionCellID];
    //设置collectionView背景色：若不设置背景为黑色
    self.itemCollectionView.backgroundColor = self.view.backgroundColor;
    
    //下拉刷新
    self.itemCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //首次进入直接下拉刷新
    [self.itemCollectionView.mj_header beginRefreshing];
    
    //上拉加载
    self.itemCollectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.view addSubview:self.itemCollectionView];
}

#pragma mark - 下拉刷新
-(void) loadNewData
{
    [self loadItemInfoWithURL:@"http://api.dantangapp.com/v2/items?generation=2&gender=1&limit=20&offset=0" andType:0];
}
#pragma mark - 上拉加载
-(void) loadMoreData
{
    if (self.next_url != nil && ![self.next_url isEqual:[NSNull null]]) {
        [self loadItemInfoWithURL:_next_url andType:1];
    } else {
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
    }
}

-(void) loadItemInfoWithURL:(NSString *)urlString andType:(NSInteger)type
{
    [[DTNetWork sharedNetWork] loadDataInfo:urlString parameters:nil success:^(id  _Nullable responseObject) {
        NSArray *items = responseObject[@"data"][@"items"];
        NSMutableArray *data = [NSMutableArray array];
        //for in 循环拿取数据
        for (NSDictionary *dict in items) {
            NSDictionary *item = dict[@"data"];
            [data addObject:item];
            
            //拿到下一页的地址
            self.next_url = responseObject[@"data"][@"paging"][@"next_url"];
            if (type == 0) {
                self.items = data;
            } else {
                [self.items addObjectsFromArray:data];
            }
            //刷新列表
            [self.itemCollectionView reloadData];
            //关闭刷新加载
            [self.itemCollectionView.mj_header endRefreshing];
            [self.itemCollectionView.mj_footer endRefreshing];
        }
    } failure:^(NSError * _Nullable error) {
        //关闭刷新加载
        [self.itemCollectionView.mj_header endRefreshing];
        [self.itemCollectionView.mj_footer endRefreshing];
    }];
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.items.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DTItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:itemCollectionCellID forIndexPath:indexPath];
    cell.items = self.items[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ItemDetailViewController *itemVC = [[ItemDetailViewController alloc]init];
    itemVC.item = self.items[indexPath.row];
    [self.navigationController pushViewController:itemVC animated:YES];
}

#pragma mark - 设置item的宽和高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = ([UIScreen mainScreen].bounds.size.width - 20) / 2;
    CGFloat height = 245;
    return CGSizeMake(width, height);
}
#pragma mark - item的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

@end
